import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  InputNumber,
  Switch,
  Tag,
  Popconfirm,
  message,
  Row,
  Col,
  Divider,
  Tooltip,
  Alert
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  CopyOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  SettingOutlined,
  InfoCircleOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Option } = Select;
const { TextArea } = Input;

// 报警规则接口
interface AlarmRule {
  id: string;
  name: string;
  description: string;
  type: 'threshold' | 'status' | 'time' | 'custom';
  level: 'low' | 'medium' | 'high' | 'critical';
  deviceType: string;
  buildingId?: string;
  buildingName?: string;
  conditions: {
    parameter: string;
    operator: string;
    value: any;
    unit?: string;
  }[];
  actions: {
    type: 'notification' | 'email' | 'sms' | 'webhook';
    target: string;
    template?: string;
  }[];
  enabled: boolean;
  triggerCount: number;
  lastTriggered?: string;
  createTime: string;
  updateTime: string;
  creator: string;
}

// 模拟报警规则数据
const mockRulesData: AlarmRule[] = [
  {
    id: 'RULE001',
    name: '电梯故障检测',
    description: '检测电梯运行状态异常，当电梯停止运行超过5分钟时触发报警',
    type: 'status',
    level: 'critical',
    deviceType: 'elevator',
    buildingId: '3',
    buildingName: '华发新城C座',
    conditions: [
      { parameter: 'status', operator: 'equals', value: 'stopped' },
      { parameter: 'duration', operator: 'greater_than', value: 5, unit: 'minutes' }
    ],
    actions: [
      { type: 'notification', target: 'maintenance_team', template: '电梯故障通知' },
      { type: 'email', target: 'maintenance@company.com' }
    ],
    enabled: true,
    triggerCount: 12,
    lastTriggered: '2024-03-15 14:30:25',
    createTime: '2024-03-01 09:00:00',
    updateTime: '2024-03-10 16:20:15',
    creator: '张工程师'
  },
  {
    id: 'RULE002',
    name: '空调温度异常',
    description: '监控空调系统温度，当温度超出正常范围时发出报警',
    type: 'threshold',
    level: 'high',
    deviceType: 'hvac',
    conditions: [
      { parameter: 'temperature', operator: 'greater_than', value: 28, unit: '°C' },
      { parameter: 'temperature', operator: 'less_than', value: 18, unit: '°C' }
    ],
    actions: [
      { type: 'notification', target: 'facility_team' },
      { type: 'sms', target: '13800138000' }
    ],
    enabled: true,
    triggerCount: 8,
    lastTriggered: '2024-03-15 09:45:12',
    createTime: '2024-02-15 14:30:00',
    updateTime: '2024-03-05 11:15:30',
    creator: '李技师'
  },
  {
    id: 'RULE003',
    name: '门禁异常访问',
    description: '检测门禁系统异常访问行为，连续失败尝试超过3次时报警',
    type: 'threshold',
    level: 'medium',
    deviceType: 'access',
    buildingId: '1',
    buildingName: '华发新城A座',
    conditions: [
      { parameter: 'failed_attempts', operator: 'greater_than', value: 3 },
      { parameter: 'time_window', operator: 'within', value: 10, unit: 'minutes' }
    ],
    actions: [
      { type: 'notification', target: 'security_team' },
      { type: 'webhook', target: 'https://api.security.com/alert' }
    ],
    enabled: true,
    triggerCount: 5,
    lastTriggered: '2024-03-14 22:15:45',
    createTime: '2024-02-20 10:00:00',
    updateTime: '2024-03-01 09:30:20',
    creator: '王管理员'
  },
  {
    id: 'RULE004',
    name: '消防系统离线检测',
    description: '监控消防系统在线状态，设备离线超过2分钟立即报警',
    type: 'status',
    level: 'critical',
    deviceType: 'fire',
    conditions: [
      { parameter: 'online_status', operator: 'equals', value: 'offline' },
      { parameter: 'offline_duration', operator: 'greater_than', value: 2, unit: 'minutes' }
    ],
    actions: [
      { type: 'notification', target: 'emergency_team' },
      { type: 'email', target: 'fire@company.com' },
      { type: 'sms', target: '13900139000' }
    ],
    enabled: true,
    triggerCount: 2,
    lastTriggered: '2024-03-12 16:20:30',
    createTime: '2024-01-15 08:00:00',
    updateTime: '2024-02-28 14:45:10',
    creator: '赵队长'
  },
  {
    id: 'RULE005',
    name: '照明系统能耗监控',
    description: '监控照明系统能耗，当功耗异常增高时提醒检查',
    type: 'threshold',
    level: 'low',
    deviceType: 'lighting',
    conditions: [
      { parameter: 'power_consumption', operator: 'greater_than', value: 150, unit: 'kW' }
    ],
    actions: [
      { type: 'notification', target: 'energy_team' }
    ],
    enabled: false,
    triggerCount: 0,
    createTime: '2024-03-10 15:30:00',
    updateTime: '2024-03-10 15:30:00',
    creator: '陈电工'
  }
];

const AlarmRules: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [rulesData, setRulesData] = useState<AlarmRule[]>(mockRulesData);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRule, setEditingRule] = useState<AlarmRule | null>(null);
  const [form] = Form.useForm();

  // 获取等级标签样式
  const getLevelTag = (level: string) => {
    const config = {
      critical: { color: 'red', text: '紧急' },
      high: { color: 'orange', text: '重要' },
      medium: { color: 'blue', text: '一般' },
      low: { color: 'green', text: '轻微' }
    };
    const { color, text } = config[level as keyof typeof config] || config.low;
    return <Tag color={color}>{text}</Tag>;
  };

  // 获取类型标签样式
  const getTypeTag = (type: string) => {
    const config = {
      threshold: { color: 'blue', text: '阈值监控' },
      status: { color: 'purple', text: '状态监控' },
      time: { color: 'orange', text: '时间监控' },
      custom: { color: 'gray', text: '自定义' }
    };
    const { color, text } = config[type as keyof typeof config] || config.custom;
    return <Tag color={color}>{text}</Tag>;
  };

  // 获取设备类型标签
  const getDeviceTypeTag = (deviceType: string) => {
    const config = {
      elevator: { color: 'blue', text: '电梯' },
      hvac: { color: 'cyan', text: '空调' },
      security: { color: 'purple', text: '安防' },
      fire: { color: 'red', text: '消防' },
      access: { color: 'orange', text: '门禁' },
      lighting: { color: 'yellow', text: '照明' }
    };
    const { color, text } = config[deviceType as keyof typeof config] || { color: 'gray', text: deviceType };
    return <Tag color={color}>{text}</Tag>;
  };

  // 新增规则
  const handleAdd = () => {
    setEditingRule(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 编辑规则
  const handleEdit = (record: AlarmRule) => {
    setEditingRule(record);
    form.setFieldsValue({
      ...record,
      conditions: record.conditions.map(c => `${c.parameter} ${c.operator} ${c.value} ${c.unit || ''}`).join('\n'),
      actions: record.actions.map(a => `${a.type}: ${a.target}`).join('\n')
    });
    setModalVisible(true);
  };

  // 复制规则
  const handleCopy = (record: AlarmRule) => {
    const newRule = {
      ...record,
      id: `RULE${Date.now()}`,
      name: `${record.name} - 副本`,
      enabled: false,
      triggerCount: 0,
      lastTriggered: undefined,
      createTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
      updateTime: new Date().toISOString().slice(0, 19).replace('T', ' ')
    };
    setRulesData([...rulesData, newRule]);
    message.success('规则复制成功');
  };

  // 删除规则
  const handleDelete = async (id: string) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 500));
      setRulesData(rulesData.filter(rule => rule.id !== id));
      message.success('规则删除成功');
    } catch (error) {
      message.error('删除失败');
    } finally {
      setLoading(false);
    }
  };

  // 启用/禁用规则
  const handleToggleEnabled = async (id: string, enabled: boolean) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 300));
      setRulesData(rulesData.map(rule => 
        rule.id === id 
          ? { ...rule, enabled, updateTime: new Date().toISOString().slice(0, 19).replace('T', ' ') }
          : rule
      ));
      message.success(`规则已${enabled ? '启用' : '禁用'}`);
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 保存规则
  const handleSave = async (values: any) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1000));

      const ruleData = {
        ...values,
        id: editingRule?.id || `RULE${Date.now()}`,
        conditions: values.conditions?.split('\n').map((line: string) => {
          const parts = line.trim().split(' ');
          return {
            parameter: parts[0],
            operator: parts[1],
            value: parts[2],
            unit: parts[3] || undefined
          };
        }) || [],
        actions: values.actions?.split('\n').map((line: string) => {
          const [type, target] = line.trim().split(': ');
          return { type, target };
        }) || [],
        triggerCount: editingRule?.triggerCount || 0,
        lastTriggered: editingRule?.lastTriggered,
        createTime: editingRule?.createTime || new Date().toISOString().slice(0, 19).replace('T', ' '),
        updateTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
        creator: editingRule?.creator || '当前用户'
      };

      if (editingRule) {
        setRulesData(rulesData.map(rule => rule.id === editingRule.id ? ruleData : rule));
        message.success('规则更新成功');
      } else {
        setRulesData([...rulesData, ruleData]);
        message.success('规则创建成功');
      }

      setModalVisible(false);
      form.resetFields();
    } catch (error) {
      message.error('保存失败');
    } finally {
      setLoading(false);
    }
  };

  // 表格列配置
  const columns: ColumnsType<AlarmRule> = [
    {
      title: '规则名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      ellipsis: true,
      render: (text, record) => (
        <div>
          <div style={{ fontWeight: 500 }}>{text}</div>
          <div style={{ fontSize: 12, color: '#666', marginTop: 2 }}>
            {record.description}
          </div>
        </div>
      )
    },
    {
      title: '规则类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type) => getTypeTag(type)
    },
    {
      title: '报警等级',
      dataIndex: 'level',
      key: 'level',
      width: 100,
      render: (level) => getLevelTag(level)
    },
    {
      title: '设备类型',
      dataIndex: 'deviceType',
      key: 'deviceType',
      width: 100,
      render: (deviceType) => getDeviceTypeTag(deviceType)
    },
    {
      title: '适用楼宇',
      dataIndex: 'buildingName',
      key: 'buildingName',
      width: 150,
      ellipsis: true,
      render: (buildingName) => buildingName || '全部楼宇'
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
      width: 80,
      render: (enabled, record) => (
        <Switch
          checked={enabled}
          onChange={(checked) => handleToggleEnabled(record.id, checked)}
          loading={loading}
          checkedChildren="启用"
          unCheckedChildren="禁用"
        />
      )
    },
    {
      title: '触发次数',
      dataIndex: 'triggerCount',
      key: 'triggerCount',
      width: 100,
      sorter: (a, b) => a.triggerCount - b.triggerCount,
      render: (count) => (
        <Tag color={count > 10 ? 'red' : count > 5 ? 'orange' : 'green'}>
          {count}
        </Tag>
      )
    },
    {
      title: '最近触发',
      dataIndex: 'lastTriggered',
      key: 'lastTriggered',
      width: 150,
      render: (time) => time || '未触发'
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      key: 'creator',
      width: 100
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="编辑">
            <Button 
              type="primary" 
              size="small" 
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="复制">
            <Button 
              size="small" 
              icon={<CopyOutlined />}
              onClick={() => handleCopy(record)}
            />
          </Tooltip>
          <Popconfirm
            title="确认删除此规则？"
            onConfirm={() => handleDelete(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button 
                danger 
                size="small" 
                icon={<DeleteOutlined />}
                loading={loading}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div className="alarm-rules-container">
      {/* 页面头部 */}
      <Card style={{ marginBottom: 16 }}>
        <Row justify="space-between" align="middle">
          <Col>
            <Space>
              <SettingOutlined style={{ fontSize: 20, color: '#1890ff' }} />
              <span style={{ fontSize: 16, fontWeight: 500 }}>报警规则管理</span>
              <Tag color="blue">共 {rulesData.length} 条规则</Tag>
              <Tag color="green">启用 {rulesData.filter(r => r.enabled).length} 条</Tag>
            </Space>
          </Col>
          <Col>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新增规则
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 使用说明 */}
      <Alert
        message="规则配置说明"
        description="报警规则基于3D页面数据管理系统的设备数据进行监控。您可以配置不同类型的监控条件，包括阈值监控、状态监控、时间监控等，系统将根据规则自动触发相应的报警通知。"
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />

      {/* 规则列表 */}
      <Card>
        <Table
          columns={columns}
          dataSource={rulesData}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1200 }}
          pagination={{
            total: rulesData.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          }}
        />
      </Card>

      {/* 规则编辑弹窗 */}
      <Modal
        title={editingRule ? '编辑报警规则' : '新增报警规则'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        confirmLoading={loading}
        width={800}
        destroyOnHidden
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
          initialValues={{
            enabled: true,
            level: 'medium',
            type: 'threshold'
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="规则名称"
                name="name"
                rules={[{ required: true, message: '请输入规则名称' }]}
              >
                <Input placeholder="请输入规则名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="规则类型"
                name="type"
                rules={[{ required: true, message: '请选择规则类型' }]}
              >
                <Select placeholder="请选择规则类型">
                  <Option value="threshold">阈值监控</Option>
                  <Option value="status">状态监控</Option>
                  <Option value="time">时间监控</Option>
                  <Option value="custom">自定义</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="报警等级"
                name="level"
                rules={[{ required: true, message: '请选择报警等级' }]}
              >
                <Select placeholder="请选择报警等级">
                  <Option value="low">轻微</Option>
                  <Option value="medium">一般</Option>
                  <Option value="high">重要</Option>
                  <Option value="critical">紧急</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="设备类型"
                name="deviceType"
                rules={[{ required: true, message: '请选择设备类型' }]}
              >
                <Select placeholder="请选择设备类型">
                  <Option value="elevator">电梯</Option>
                  <Option value="hvac">空调</Option>
                  <Option value="security">安防</Option>
                  <Option value="fire">消防</Option>
                  <Option value="access">门禁</Option>
                  <Option value="lighting">照明</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="适用楼宇"
                name="buildingName"
              >
                <Select placeholder="选择楼宇（留空表示全部楼宇）" allowClear>
                  <Option value="华发新城A座">华发新城A座</Option>
                  <Option value="商业综合体">商业综合体</Option>
                  <Option value="华发新城C座">华发新城C座</Option>
                  <Option value="商业中心">商业中心</Option>
                  <Option value="华发二期办公楼D座">华发二期办公楼D座</Option>
                  <Option value="华发二期住宅楼5号楼">华发二期住宅楼5号楼</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="规则状态"
                name="enabled"
                valuePropName="checked"
              >
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            label="规则描述"
            name="description"
            rules={[{ required: true, message: '请输入规则描述' }]}
          >
            <TextArea rows={3} placeholder="请描述此规则的用途和触发条件" />
          </Form.Item>

          <Divider />

          <Form.Item
            label={
              <Space>
                <span>监控条件</span>
                <Tooltip title="每行一个条件，格式：参数名 操作符 值 单位">
                  <InfoCircleOutlined />
                </Tooltip>
              </Space>
            }
            name="conditions"
            rules={[{ required: true, message: '请输入监控条件' }]}
          >
            <TextArea 
              rows={4} 
              placeholder={`示例：
temperature greater_than 28 °C
status equals offline
duration greater_than 5 minutes`}
            />
          </Form.Item>

          <Form.Item
            label={
              <Space>
                <span>报警动作</span>
                <Tooltip title="每行一个动作，格式：动作类型: 目标">
                  <InfoCircleOutlined />
                </Tooltip>
              </Space>
            }
            name="actions"
            rules={[{ required: true, message: '请输入报警动作' }]}
          >
            <TextArea 
              rows={3} 
              placeholder={`示例：
notification: maintenance_team
email: admin@company.com
sms: 13800138000`}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AlarmRules;